import mongoose, { Document, Schema } from 'mongoose'
import dayjs from 'dayjs'
import { Counter } from './counter'

export interface IMenu extends Document {
  id: number
  name: string
  code: string
  path: string
  description: string
  parent_id: number | null
  level: number
  sort_order: number
  icon: string
  is_visible: boolean
  created_at: string
  updated_at: string
  created_by: number | null
  updated_by: number | null
}

const MenuSchema: Schema = new Schema({
  id: {
    type: Number,
    unique: true,
    description: '菜单id'
  },
  name: {
    type: String,
    unique: true,
    required: true,
    description: '菜单名称'
  },
  code: {
    type: String,
    unique: true,
    required: true,
    description: '菜单编码，用于系统标识'
  },
  path: {
    type: String,
    required: true,
    description: '菜单路径'
  },
  description: {
    type: String,
    required: false,
    default: '',
    description: '菜单描述'
  },
  parent_id: {
    type: Number,
    default: null,
    description: '父菜单id，顶级菜单为null'
  },
  level: {
    type: Number,
    required: true,
    default: 1,
    description: '菜单层级，从1开始'
  },
  sort_order: {
    type: Number,
    default: 0,
    description: '排序号，值越小越靠前'
  },
  icon: {
    type: String,
    required: false,
    default: '',
    description: '菜单图标'
  },
  is_visible: {
    type: Boolean,
    default: true,
    description: '是否可见'
  },
  created_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  }
})

// 保存前处理
MenuSchema.pre<IMenu>('save', async function (next) {
  if (this.isNew) {
    try {
      // 设置默认层级
      if (!this.level && this.parent_id) {
        const parentMenu = await mongoose
          .model<IMenu>('menu')
          .findOne({ id: this.parent_id })
        if (parentMenu) {
          this.level = parentMenu.level + 1
        } else {
          this.level = 1
        }
      } else if (!this.level) {
        this.level = 1
      }

      const counter = await Counter.findByIdAndUpdate(
        { _id: 'menu_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      )
      this.id = counter.seq
      next()
    } catch (error: any) {
      next(error)
    }
  } else {
    next()
  }
})

// 更新时更新时间戳
MenuSchema.pre<IMenu>('findOneAndUpdate', function (next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') })
  next()
})

// 配置 toJSON 输出
MenuSchema.set('toJSON', {
  transform: function (doc, ret) {
    const { _id, __v, ...rest } = ret
    return rest
  }
})

export const Menu = mongoose.model<IMenu>('menu', MenuSchema, 'menu')
